Dependency injection (DI) is a design pattern in object-oriented computer programming whose purpose is to reduce the coupling between software components. Frequently an object uses (depends on) work produced by another part of the system. With DI, the object does not need to know in advance about how the other part of the system works. Instead, the programmer provides (injects) the relevant system component in advance.
Instead of hard-coding the dependencies, a component just lists the necessary services and a DI framework supplies these. At runtime, an independent component will load and configure components such as the database driver and offer a standard interface to interact with the database. The details have been moved from the original component to a set of new, small, database-specific components, reducing the complexity of them all. In DI terms, these new components are called “service components”, as they render a service (database access) for one or more other components.
One benefit of using the dependency injection approach is the reduction of boilerplate code in the application objects since all work to initialize or set up dependencies is handled by a provider component. Another benefit is that it offers configuration flexibility because alternative implementations of a given service can be used without recompiling code. This is useful in unit testing, as it is easy to inject a fake implementation of a service into the object being tested by changing the configuration file.
However, there should be a definite reason for moving a dependency away from the object that needs it. One drawback is that excessive or inappropriate use of dependency injection can make applications more complicated, harder to understand, and more difficult to modify. Code that uses dependency injection can seem incomprehensible to some developers, since instantiation and initialization of objects is handled completely separately from the code that uses them. This separation can also result in problems that are hard to diagnose.